import React, { useEffect, useState, useRef, useMemo } from 'react';
import { NavigationProp, RouteProp } from '@react-navigation/native';
import { StyleSheet, TouchableOpacity, View, Text, Image, TextInput, Button, Alert, TouchableHighlight } from 'react-native';
import { useSelector } from 'react-redux';
import { CommonStyle } from '../../../common/commonStyle.ts';
import { Loading } from '../../../component/LoadingOverlay.tsx';
import { AppDispatch, RootState } from '../../../redux/store.ts';
import AntDesign from 'react-native-vector-icons/AntDesign';
import FontAwesome5 from 'react-native-vector-icons/AntDesign';
import HomeRequest from '../../../request/homeRequest.ts';
import CustomFlatList from '../../../component/CustomFlatList.tsx';
import { useReactive } from 'ahooks';
import { Badge, Actionsheet, useDisclose, Stack, Center, ScrollView } from 'native-base';
import { ShowConfirmDialog } from '../../../component/ConfirmDialog.tsx';
import GridLayout from '../../../component/GridLayout.tsx';
import InfoCard from '../../../component/InfoCard.tsx';
import Cell from '../../../component/Cell.tsx';
import { EAlarmType } from '../../../common/enum.ts';
import { useToast } from 'react-native-toast-notifications';
import Tools from '../../../utils/Tools.ts';

interface IInformDetailsProps {
  navigation: NavigationProp<any, 'activityDetail'>;
  route: RouteProp<{ activityDetail: any }, 'activityDetail'>;
}

interface IMenuList {
  id: number;
  name: string;
  iconName: string;
}

interface ICardList {
  label: string;
}

interface IStatistics {
  name: string;
  value: number;
}

interface IData {
  menuList: IMenuList[];
  cardList: ICardList[];
  info?: IGetNotifyDetail;
  statisticsList: IStatistics[];
  phoneList: string[];
}

const InformDetails: React.FC<IInformDetailsProps> = ({ navigation, route }) => {
  const { isOpen, onOpen, onClose } = useDisclose();

  const beeperId = useSelector((state: RootState) => state.beeperId);

  const data = useReactive<IData>({
    menuList: [
      {
        iconName: 'profile',
        name: '通知列表',
        id: 1,
      },
      {
        iconName: 'phone',
        name: '一键重播',
        id: 2,
      },
    ],
    cardList: [],
    statisticsList: [],
    info: undefined,
    phoneList: [],
  });

  const cardIcon = {
    iconName: 'reload1',
    size: 18,
    color: '#000',
  };

  const toast = useToast();

  const [viewWidth, setViewWidth] = useState(0);

  const [viewWidthTj, setViewWidthTj] = useState(0);

  const viewLayout = (event: any) => {
    let { x, y, width, height } = event.nativeEvent.layout;
    setViewWidth(width);
  };

  const viewLayoutTj = (event: any) => {
    let { x, y, width, height } = event.nativeEvent.layout;
    setViewWidthTj(width);
  };

  const menuChange = (id: number) => {
    switch (id) {
      case 1:
        navigation.navigate('informList');
        break;

      case 2:
        HomeRequest.OnekeyReport({ notifyId: data.info!.notifyId })
          .then((res) => {
            if (res.data === null) {
              toast.show('操作成功', { placement: 'bottom' });
              setTimeout(() => {
                getNotifyDetails();
              }, 1000);
            }
          })
          .catch((err) => {});
        break;
    }
  };

  const renderItem = (item: IMenuList, index: number) => {
    return (
      <TouchableOpacity
        onPress={() => {
          menuChange(item.id);
        }}
        style={[styles.gridStyle, { width: viewWidth / 4 }]}
      >
        <AntDesign name={item.iconName} size={26} color={'#000'}></AntDesign>
        <Text style={{ color: '#646566', marginTop: 10, fontSize: 12, fontWeight: 'bold' }}>{item.name}</Text>
      </TouchableOpacity>
    );
  };

  const renderItemTj = (item: IStatistics, index: number) => {
    return (
      <View style={[styles.gridStyleTj, { width: viewWidthTj / 4 }]}>
        <View>
          <Text style={{ color: '#000', marginTop: 10, fontWeight: 'bold' }}>{item.name}</Text>
        </View>
        <View>
          <Text style={{ color: '#000', marginTop: 10, fontWeight: 'bold' }}>{item.value}</Text>
        </View>
      </View>
    );
  };

  const cardChange = (state: string | number) => {
    if (state === 'reload1') {
      getMx();
    }
  };

  const getNotifyDetails = () => {
    Loading.show('正在加载中');
    let params: any = { beeperId: beeperId };
    if (route.params && route.params.notifyId) {
      HomeRequest.GetNotifyDetailId({ notifyId: route.params.notifyId, ...params })
        .then((res) => {
          Loading.hide();
          data.info = res.data;
          data.info.typeName = EAlarmType[data.info.notifyType as keyof typeof EAlarmType];
          getStatisticsList(data.info!.notifyId);
        })
        .catch((err) => {
          Loading.hide();
        });
    } else {
      HomeRequest.GetNotifyDetail(params)
        .then((res) => {
          Loading.hide();
          data.info = res.data;
          data.info.typeName = EAlarmType[data.info.notifyType as keyof typeof EAlarmType];
          getStatisticsList(data.info!.notifyId);
        })
        .catch((err) => {
          Loading.hide();
        });
    }
  };

  const getMx = () => {
    HomeRequest.GetMxList({ notifyId: data.info!.notifyId })
      .then((res) => {
        toast.show('更新成功', { placement: 'bottom' });
        data.info!.taskRecordList = res.data;
        getStatisticsList(data.info!.notifyId);
      })
      .catch((err) => {
        Loading.hide();
      });
  };

  const getStatisticsList = (notifyId: number) => {
    HomeRequest.GetNotifyStatistics({ notifyId })
      .then((res) => {
        const datas: IGetNotifyStatistics = res.data;
        const keyOrder: Array<keyof typeof datas> = ['sumHouse', 'successHouse', 'notifyPhone', 'connectedPhone'];
        const dataArray = keyOrder.map((key) => {
          let name;
          switch (key) {
            case 'sumHouse':
              name = '通知户数';
              break;
            case 'successHouse':
              name = '成功户数';
              break;
            case 'notifyPhone':
              name = '通知人数';
              break;
            case 'connectedPhone':
              name = '接通人数';
              break;
            default:
              name = 'Unknown';
          }
          return {
            name,
            value: datas[key],
          };
        });
        data.statisticsList = dataArray;
      })
      .catch((err) => {});
  };

  useEffect(() => {
    if (route.params && route.params.notifyId) {
      data.menuList.splice(0, 1);
    }
    getNotifyDetails();
  }, [route.params]);

  const LeftChildView: React.FC<{ item: IGetMxlist }> = ({ item }) => {
    return (
      <View>
        <View>
          {item.notifyState === 1 && (
            <Badge colorScheme="info" alignSelf="flex-start" variant={'solid'}>
              通知中
            </Badge>
          )}
          {item.notifyState === 10 && (
            <Badge colorScheme="success" alignSelf="flex-start" variant={'solid'}>
              通知成功
            </Badge>
          )}
          {item.notifyState === -1 && (
            <Badge colorScheme="error" alignSelf="flex-start" variant={'solid'}>
              通知失败
            </Badge>
          )}
        </View>
        <View style={{ flexDirection: 'row', marginTop: 4, alignItems: 'center' }}>
          <AntDesign name="enviroment" color={'#808e9b'} size={16}></AntDesign>
          <Text style={{ fontSize: 14, color: '#000', marginLeft: 4 }}>{item.address}</Text>
        </View>
      </View>
    );
  };

  const RightChildView: React.FC<{ item: IGetMxlist }> = ({ item }) => {
    return (
      <View>
        <AntDesign
          name="phone"
          size={20}
          color={'#000'}
          onPress={() => {
            phoneFilter(item.phones);
          }}
        ></AntDesign>
      </View>
    );
  };

  const phoneFilter = (phones: string) => {
    if (!phones) {
      toast.show('暂无可拨打号码', { placement: 'bottom' });
      return;
    }
    if (phones.includes(',')) {
      data.phoneList = phones.split(',');
    } else {
      data.phoneList = [phones];
    }
    onOpen();
  };

  return (
    <ScrollView style={styles.container}>
      <View
        onLayout={(e) => {
          viewLayout(e);
        }}
        style={styles.gridView}
      >
        <GridLayout menuList={data.menuList} renderItem={({ item, index }) => renderItem(item, index)}></GridLayout>
      </View>
      <InfoCard cardTitle="通知信息">
        {data.info && (
          <View>
            <Cell isSlot={false} title="事故发生地" val={data.info.address}></Cell>
            <Cell isSlot={false} title="事故类型" val={data.info.typeName!}></Cell>
            <Cell isSlot={false} title="发生时间" val={data.info.createDate}></Cell>
          </View>
        )}
      </InfoCard>
      <InfoCard cardTitle="通知统计">
        <View
          onLayout={(e) => {
            viewLayoutTj(e);
          }}
          style={styles.gridView}
        >
          <GridLayout menuList={data.statisticsList} renderItem={({ item, index }) => renderItemTj(item, index)}></GridLayout>
        </View>
      </InfoCard>
      <InfoCard cardTitle="通知明细" cardIcon={cardIcon} cardChange={cardChange}>
        {data.info && data.info.taskRecordList.map((item, index) => <Cell key={index} isSlot={true} leftChild={<LeftChildView item={item} />} rightChild={<RightChildView item={item} />}></Cell>)}
      </InfoCard>
      <Actionsheet isOpen={isOpen} onClose={onClose}>
        <Actionsheet.Content>
          {data.phoneList.map((item, index) => (
            <Actionsheet.Item key={index} onPress={() => Tools.callPhone(item)}>
              {item}
            </Actionsheet.Item>
          ))}
        </Actionsheet.Content>
      </Actionsheet>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 10,
  },
  gridView: {
    width: '100%',
    backgroundColor: '#fff',
    borderRadius: 8,
    marginBottom: 20,
  },
  gridStyle: {
    backgroundColor: '#fff',
    height: 80,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 8,
  },
  gridStyleTj: {
    backgroundColor: '#fff',
    height: 60,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 8,
  },
});

export default InformDetails;
